package com.ccteam.admin.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ccteam.admin.core.AdminCore
import com.ccteam.admin.repositories.BaseAdminRepository
import com.ccteam.admin.utils.ErrorMessage
import com.ccteam.admin.utils.Event
import com.ccteam.admin.utils.LoadMessage
import com.ccteam.admin.vo.Resource
import com.ccteam.network.ApiError
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/2/5
 **/
@HiltViewModel
class MainActivityViewModel @Inject constructor(
    private val adminRepository: BaseAdminRepository,
    private val adminCore: AdminCore
): ViewModel() {

    private val _adminName = MutableLiveData<String>()
    val adminName: LiveData<String> get() = _adminName

    private val _logoutLoadMessage = MutableLiveData<Event<LoadMessage>>()
    val logoutLoadMessage: LiveData<Event<LoadMessage>> get() = _logoutLoadMessage

    init {
        viewModelScope.launch {
            adminCore.userInfo.collectLatest {
                _adminName.value = it.adminName
            }
        }
    }

    /**
     * 登出
     */
    fun logout(){
        viewModelScope.launch {
            adminRepository.logoutAdmin(adminCore.userInfo.value.adminToken)
            adminCore.logout()
            _logoutLoadMessage.value = Event(LoadMessage.Success)
        }
    }
}